﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using oAuth;
using System.Net;
namespace Twicko {
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class LoginWindow : Window {
        oAuthTwitter oAuth;
        public LoginWindow(oAuthTwitter oAuth) {
            InitializeComponent();
            this.oAuth = oAuth;
            oAuth.ConsumerKey = "xxx";
            oAuth.ConsumerSecret = "xxx";
            webBrowser.Source = new Uri(oAuth.AuthorizationLinkGet());
        }


        private void btnSolicitarAutenticacao_Click(object sender, RoutedEventArgs e) {
            System.Diagnostics.Process.Start(oAuth.AuthorizationLinkGet());

        }

        private void btnAutorizar_Click(object sender, RoutedEventArgs e) {
            //oAuth.AccessTokenGet(oAuth.Token, txtPIN.Text.Trim());
        }

        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e) {
            try {

                string action = null;
                string pin = null;
                if ((webBrowser.Document as mshtml.IHTMLDocument3).getElementById("twitainer") != null && (webBrowser.Document as mshtml.IHTMLDocument3).getElementById("twitainer").innerHTML.Contains("?denied=")) {
                    action = "denied";
                } else if ((webBrowser.Document as mshtml.IHTMLDocument3).getElementById("oauth_pin") != null) {
                    action = "authorized";
                    pin = (webBrowser.Document as mshtml.IHTMLDocument3).getElementById("oauth_pin").innerText.Trim();
                }

                if (!String.IsNullOrEmpty(action) && (action.Equals("authorized") || action.Equals("denied"))) {
                    if (pin != null) {
                        oAuth.AccessTokenGet(oAuth.Token, pin);
                    }
                    this.Close();
                }
            } catch (Exception ex) {
                MessageBox.Show("Ocorreu um erro ao executar esta operação, tente novamente.", "Erro", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(ex.Message);
                this.Close();
            }
        }

    }
}
